package cc.wanforme.chipmunity.system.service;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cc.wanforme.chipmunity.common.PassEncoder;
import cc.wanforme.chipmunity.common.bean.WebResponse;
import cc.wanforme.chipmunity.system.Enum.RoleEnum;
import cc.wanforme.chipmunity.system.mapper.user.UserMapper;
import cc.wanforme.chipmunity.system.po.user.User;
import cc.wanforme.chipmunity.system.service.interfaces.UserService;

/**
 * @author wanne
 * 2019年7月24日
 * 
 */
@Service
public class UserSereviceImpl implements UserService{
	private static final Logger log = LoggerFactory.getLogger(UserSereviceImpl.class);
	
	@Autowired
	private UserMapper userMapper;
	
	@Transactional
	@Override
	public WebResponse saveUser(User user, String password) {
		//逻辑处理
		if(StringUtils.isBlank(user.getUsername())) {
			return WebResponse.fail("用户名不能为空");
		}else if(user.getUsername().length()>100) {
			return WebResponse.fail("用户名太长");
		}
		if(StringUtils.isBlank(user.getPassword())) {
			return WebResponse.fail("密码不能为空");
		}
		if(!user.getPassword().equals(password)) {
			return WebResponse.fail("密码不一致");
		}
		//检查用户名唯一
		User userExisted = userMapper.selectUserByUsername(user.getUsername());
		if(userExisted != null) {
			return WebResponse.fail("用户名已存在");
		}
				
		//密码加密 和 设置默认角色
		try {
			user.setPassword(PassEncoder.encodePassword(user.getPassword()));
		} catch (UnsupportedEncodingException e) {
			log.info("加密失败！");
			log.error(e.getMessage());
			return WebResponse.success("注册失败");
		}
		user.setRole(RoleEnum.USER.getName());
		//昵称设置为用户名
		user.setName(user.getUsername());
		user.setRegisterTime(new Date());
		
		//保存
		userMapper.insertUser(user);
		return WebResponse.success("注册成功");
	}

	@Override
	public User selectUserByUserName(String username) {
		return userMapper.selectUserByUsername(username);
	}

}
